package com.party.admin.task;

import com.party.admin.biz.order.OrderBizService;
import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.core.model.order.OrderFormSubInfo;
import com.party.core.service.order.IOrderFormService;
import com.party.core.service.order.IOrderFormSubInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 订单相关定时任务
 * Created by wei.li
 *
 * @date 2017/3/30 0030
 * @time 17:30
 */
@Component(value = "quartzOrder")
public class QuartzOrder {

    @Autowired
    private IOrderFormService orderFormService;
    @Autowired
    private OrderBizService orderBizService;
    @Autowired
    private IOrderFormSubInfoService orderFormSubInfoService;

    protected static Logger logger = LoggerFactory.getLogger(QuartzOrder.class);


    /**
     * 作废订单
     */
    public void refresh() {
//        List<OrderForm> orderFormList = orderFormService.invalidList();
//        for (OrderForm orderForm : orderFormList) {
//            try {
//                orderBizService.invalid(orderForm);
//                logger.info("订单作废成功");
//            } catch (Exception e) {
//                logger.error("订单作废异常", e);
//                continue;
//            }
//        }
    }

    /**
     * 删除作废订单
     * (每周六 23:59 执行)
     */
    public void clean() {
//        Set<Integer> status = Sets.newHashSet();
//        status.add(OrderStatus.ORDER_STATUS_OTHER.getCode());
//        List<OrderForm> orderFormList = orderFormService.listPage(new OrderForm(), null, status);
//        List<String> ids = LangUtils.transform(orderFormList, new Function<OrderForm, String>() {
//            @Override
//            public String apply(OrderForm orderForm) {
//                return orderForm.getId();
//            }
//        });
//        orderFormService.batchDelete(Sets.newHashSet(ids));
//        logger.info("删除作废订单成功");
    }


    /**
     * 取消超时待支付订单
     */
    public void updateOvertimeOrderCancel() {
        try {
            logger.info("开始取消超时待支付订单~");
            Integer count = orderBizService.updateOvertimeOrderCancel();
            logger.info("结束取消超时待支付订单~影响数量：{}", count);
        } catch (Exception e) {
            logger.error("取消超时待支付订单异常", e);
        }
    }

    /**
     * 复制和删除已取消订单
     */
    public void copyAndDeleteCanceledOrder() {
        try {
            logger.info("开始复制和删除已取消订单~");
            boolean result = orderBizService.copyAndDeleteCanceledOrder();
            logger.info("结束复制和删除已取消订单~结果：{}", result);
        } catch (Exception e) {
            logger.error("结束复制和删除已取消订单异常", e);
        }
    }

    /**
     * @return void
     * @Author yifeng
     * @Description 初始化订单的附属表
     * @Date 14:58 2018/12/28
     **/
    public void insertOrderSubInfo() {
        logger.info("执行开始-----初始化订单的附属表----" + DateUtils.formatDate(new Date(), DateUtils.DATETIME_PATTERN));
        Page page = new Page(1, 1000);
        Integer totalCount = orderFormService.countForSubInfo(1);
        page.setTotalCount(totalCount);

        if (page.getTotalPages() == 0) {
            return;
        }
        ExecutorService threadPool = Executors.newFixedThreadPool(50);
        for (int i = 0; i < page.getTotalPages(); i++) {
            if (i > 99) {
                break;
            }
            int offset = i * page.getLimit();
            List<String> orderIds = orderFormService.listPageForSubInfo(1, offset, page.getLimit());
            threadPool.execute(() -> {
                for (String orderId : orderIds) {
                    try {
                        OrderFormSubInfo orderFormSubInfo = orderFormSubInfoService.getOrderWithMember(orderId, 1);
                        orderFormSubInfoService.insert(orderFormSubInfo);
                    } catch (Exception e) {
                        logger.error("初始化附属信息异常：orderId-{}", e, orderId);
                        continue;
                    }
                }
            });
        }
        logger.info("执行结束-----初始化订单的附属表----" + DateUtils.formatDate(new Date(), DateUtils.DATETIME_PATTERN));
    }
}
